package com.stars.easyms.demo.restservice.jdk8;

import com.stars.easyms.rest.RestService;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.Optional;

/**
 * <p>className: EasyMsJdk8Demo13Service</p>
 * <p>description: Map新方法</p>
 *
 * @author guoguifang
 * @date 2019/9/23 16:53
 * @since 1.3.2
 */
@Service
public class EasyMsJdk8Demo13Service implements RestService<Void, Void> {

    @Override
    public Void execute(Void input) {
        Map<String, String> map = new HashMap<>(32);

        // 如果key存在则返回value，如果key不存在则设置value并返回该value
        System.out.println(map.get("a"));
        System.out.println(map.getOrDefault("a", "default"));
        String newValue = map.computeIfAbsent("a", key -> "b");
        System.out.println(newValue + "," + map.get("a"));
        newValue = map.computeIfAbsent("a", key -> "c");
        System.out.println(newValue + "," + map.get("a"));

        // 如果key存在则返回value，如果key不存在则设置value并返回该value
        newValue = map.computeIfPresent("a", (key, oldValue) -> "b".equals(oldValue) ? "d" : "f");
        System.out.println(newValue + "," + map.get("a"));

        // foreach方法
        map.forEach((key, value) -> System.out.println(key + ":" + value));

        return null;
    }

}